const app = getApp()
const api = require('../../utils/api.js')
Page({
    data: {
        userInfo: {},
        hasUserInfo: false,
        canIUse: wx.canIUse('button.open-type.getUserInfo'),
        cardNo: '', // 卡号
        phone: wx.getStorageSync('phone'),
        levelId: 1, // 会员等级
        number: '0', // 会员积分
        userId: '', // 用户ID
        balance: 0, // 余额
        couponNumber: 0, //  优惠券张数
        userLevelName: '', // 会员等级中文
        discount: '', // 折扣
        wxopenid: '',
        wxCard: '',
        cardData:''
    },
    onLoad: function () {
        var that = this;
        if (app.globalData.userInfo) {
            this.setData({
                userInfo: app.globalData.userInfo,
                hasUserInfo: true
            })
        } else if (this.data.canIUse) {
            app.userInfoReadyCallback = res => {
                this.setData({
                    userInfo: res.userInfo,
                    hasUserInfo: true
                })
            }
        } else {
            // 在没有 open-type=getUserInfo 版本的兼容处理
            wx.getUserInfo({
                success: res => {
                    app.globalData.userInfo = res.userInfo
                    this.setData({
                        userInfo: res.userInfo,
                        hasUserInfo: true
                    })
                },
                fail: function () {
                    //获取用户信息失败后。请跳转授权页面
                    wx.showToast({
                        title: '授权后才能使用',
                        icon: 'none',
                        duration: 1500
                    })
                }
            })
        }
        if (wx.getStorageSync('user').openid) {
            this.setData({
                wxopenid: wx.getStorageSync('user').openid
            })
        }

        api.post('shop/getCardActivate',{
            shopId: app.globalData.shopId,
        }).then(res=>{
            console.log(res)
            let obj ={}
            obj['biz'] = decodeURIComponent(res.data.data.biz);
            obj['encrypt_card_id'] = decodeURIComponent(res.data.data.encrypt_card_id);
            obj['outer_str']= res.data.data.outer_str
            that.setData({
                cardData :obj
            })
        })


    },
    getUserInfo: function (e) {
        console.log(e)
        var that = this;
        app.globalData.userInfo = e.detail.userInfo
        if (e.detail.userInfo) {
            this.setData({
                userInfo: e.detail.userInfo,
                hasUserInfo: true
            });
            wx.getUserInfo({
                success: res => {
                    if (wx.getStorageSync('phone') && wx.getStorageSync('user').openid) {
                        wx.showLoading({
                            title: '加载中',
                        })
                        // 将 res 发送到后台解码出 unionid
                        api.post('user/decrypt', {
                            sessionKey: encodeURIComponent(wx.getStorageSync('user').session_key),
                            encryptedData: encodeURIComponent(res.encryptedData),
                            iv: encodeURIComponent(res.iv)
                        }).then(res => {
                            if (res.data.success) {/*  */
                                wx.setStorageSync('unionId', res.data.data.unionId);
                                // 注册登录 
                                api.post('user/getByMobile', {
                                    mobile: wx.getStorageSync('phone'),
                                    openid: wx.getStorageSync('user').openid,
                                    shopId: app.globalData.shopId,
                                    // unionid: wx.getStorageSync('unionId')
                                }).then(res => {
                                    console.log(res)
                                    // 获取用户信息
                                    if (res.data.success) {
                                        that.setData({
                                            phone: wx.getStorageSync('phone'),
                                            cardNo: res.data.data.wxCard || res.data.data.card,
                                            number: res.data.data.number,
                                            levelId: res.data.data.levelId,
                                            balance: res.data.data.totalBalance / 100 || 0,
                                            userId: res.data.data.userId,
                                            couponNumber: res.data.data.couponNumber,
                                            userLevelName: res.data.data.userLevelName,
                                            discount: res.data.data.discount
                                        })
                                    }
                                })
                                // 保存unionid
                                api.post('user/saveOpenid', {
                                    openid: wx.getStorageSync('user').openid,
                                    shopId: app.globalData.shopId,
                                    unionid: res.data.data.unionId
                                }).then(res => {
                                    console.log(res, 55)
                                })
                            }
                            wx.hideLoading()
                        })

                    }

                }
            })
        } else {
            wx.showToast({
                title: '授权后才能使用',
                icon: 'none',
                duration: 1500
            })
        }
    },
    // 领取会员卡
    clickMyCard: function (event) {
        if (!this.data.phone) {
            return wx.showToast({
                title: '激活会员，享受更多折扣福利',
                icon: 'none',
                duration: 1500
            })

        }
        var that = this
        wx.request({
            url: api.baseUrl + 'user/getSignature',
            method: 'POST',
            data: {
                cardId: app.globalData.cardId,
                shopId: app.globalData.shopId
            },
            success: function (res) {

                var cardExt = {}
                cardExt.nonce_str = res.data.data.noncestr
                cardExt.timestamp = res.data.data.timestamp
                cardExt.signature = res.data.data.signature
                wx.addCard({
                    cardList: [{
                        cardId: app.globalData.cardId,
                        cardExt: JSON.stringify(cardExt)
                    }],
                    success: function (res) {
                        that.getCardNo(res.cardList[0].code)
                    },
                    complete: function (res) {
                        console.log(res, 111) // 卡券添加结果
                    }


                })

            },
            fail: function (err) {
                console.log(err)
            }
        })

        // 保存formID
        if (!that.data.wxCard) {
            let formId = event.detail.formId;
            // 忽略开发者工具里边的formId
            if (formId && formId !== 'the formId is a mock one') {
                that.saveFormId(formId)
                console.log('formId:' + formId)
            }
        }



    },
    // 分享
    onShareAppMessage: function (ops) {
        if (ops.from === 'button') {
            // 来自页面内转发按钮
            console.log(ops.target)
        }
        return {
            title: app.globalData.appName,
            path: 'pages/user/index',
            success: function (res) {
                // 转发成功
                console.log("转发成功:" + JSON.stringify(res));
            },
            fail: function (res) {
                // 转发失败
                console.log("转发失败:" + JSON.stringify(res));
            }
        }

    },
    /* 解密卡号 */
    getCardNo: function (cardCode) {
        var that = this
        api.post('user/saveCardNum', {
            code: cardCode,
            mobile: wx.getStorageSync('phone'),
            shopId: app.globalData.shopId,
        }).then(res => {
            if (res.data.success) {
                that.setData({
                    cardNo: res.data.data.cardNum
                })
            }
        })
    },
    /* 手机号授权并注册登录 */
    getPhoneNumber: function (e) {
        var that = this;
        wx.showLoading({
            title: '加载中',
        })
        api.post('user/decrypt', {
            sessionKey: encodeURIComponent(wx.getStorageSync('user').session_key),
            encryptedData: encodeURIComponent(e.detail.encryptedData),
            iv: encodeURIComponent(e.detail.iv)
        }).then(res => {
            if (res.data.success) {

                that.setData({
                    phone: res.data.data.phoneNumber
                })
                wx.setStorageSync('phone', res.data.data.phoneNumber);
                // 注册登录 
                api.post('user/getByMobile', {
                    mobile: res.data.data.phoneNumber || wx.getStorageSync('phone'),
                    openid: wx.getStorageSync('user').openid,
                    shopId: app.globalData.shopId,
                    // unionid: wx.getStorageSync('unionId')
                }).then(response => {
                    console.log(response)
                    // 获取用户信息
                    if (response.data.success) {
                        that.setData({
                            cardNo: response.data.data.wxCard || response.data.data.card,
                            number: response.data.data.number,
                            levelId: response.data.data.levelId,
                            balance: response.data.data.totalBalance / 100 || 0,
                            userId: response.data.data.userId,
                            couponNumber: response.data.data.couponNumber,
                            userLevelName: response.data.data.userLevelName, // 会员等级中文
                            discount: response.data.data.discount, // 折扣
                            wxCard: response.data.data.wxCard,
                            phone: response.data.data.mobile,
                            hasUserInfo: true

                        })
                    }
                    // 手机号激活后没有会员直接跳转领卡
                    if (!response.data.data.wxCard) {
                        // that.clickMyCard()
                        that.openCard()
                    }

                })
                wx.hideLoading()



            }
            wx.hideLoading()
        })


    },
    /* 跳转【优惠支付】 */
    clickMyPay: function () {
        if (!this.data.phone) {
            return wx.showToast({
                title: '激活会员，享受更多折扣福利',
                icon: 'none',
                duration: 1500
            })
        }
        wx.navigateTo({
            url: '/pages/pay/index'
        })
    },
    /* 跳转【我的余额】 */
    goBalance: function () {
        if (!this.data.phone) {
            return wx.showToast({
                title: '激活会员，享受更多折扣福利',
                icon: 'none',
                duration: 1500
            })
        }
        wx.navigateTo({
            url: '/pages/balance/index?userId=' + this.data.userId + '&balance=' + this.data.balance
        })
    },
    /* 跳转【我的优惠券】 */
    goMycoupon: function () {
        if (!this.data.phone) {
            return wx.showToast({
                title: '激活会员，享受更多折扣福利',
                icon: 'none',
                duration: 1500
            })
        }
        wx.navigateTo({
            url: '/pages/mycoupons/index?userId=' + this.data.userId
        })
    },

    /* 跳转【资金记录】 */
    gocashRecorde: function () {
        if (!this.data.phone) {
            return wx.showToast({
                title: '激活会员，享受更多折扣福利',
                icon: 'none',
                duration: 1500
            })

        }
        wx.navigateTo({
            url: '/pages/cashRecorde/index?userId=' + this.data.userId
        })
    },
    /* 跳转【商家信息】 */
    goshopInfo: function () {
        if (!this.data.phone) {
            return wx.showToast({
                title: '激活会员，享受更多折扣福利',
                icon: 'none',
                duration: 1500
            })
        }
        wx.navigateTo({
            url: '/pages/shopInfo/index?userId=' + this.data.userId
        })
    },

    /* 微信授权 */
    getWXConfim: function () {
        wx.showToast({
            title: '请先授权微信',
            icon: 'none',
            duration: 1500
        })
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var that = this

        if ( that.data.phone >0 || wx.getStorageSync('phone')>0) {
            
            console.log('1:' + that.data.phone,'2:'+wx.getStorageSync('phone'))
            api.post('user/getByMobile', {
                mobile: wx.getStorageSync('phone'),
                openid: wx.getStorageSync('user').openid,
                shopId: app.globalData.shopId,
            }).then(res => {
                console.log(res)
                wx.hideLoading()
                // 获取用户信息
                if (res.data.success) {
                    that.setData({
                        cardNo: res.data.data.wxCard || res.data.data.card,
                        number: res.data.data.number,
                        levelId: res.data.data.levelId,
                        balance: res.data.data.totalBalance / 100 || 0,
                        userId: res.data.data.userId,
                        couponNumber: res.data.data.couponNumber,
                        userLevelName: res.data.data.userLevelName, // 会员等级中文
                        discount: res.data.data.discount, // 折扣
                        phone: res.data.data.mobile,
                        // hasUserInfo: true,
                    })
                }

            })
        }


    },
    saveFormId: function (id) {
        api.post('user/saveFormid', {
            openid: wx.getStorageSync('user').openid,
            shopId: app.globalData.shopId,
            formid: id
        }).then(res => {
            console.log(res)
        })
    },
    /* 开卡组件 */
    openCard: function () {
        api.post('shop/getCardActivate',{
            shopId: app.globalData.shopId,
        }).then(res=>{
            console.log(res)
            let obj ={}
            obj['biz'] =decodeURIComponent(res.data.data.biz);
            obj['encrypt_card_id'] =decodeURIComponent(res.data.data.encrypt_card_id);
            obj['outer_str']= decodeURIComponent(res.data.data.outer_str)
            wx.navigateToMiniProgram({
                appId: 'wxeb490c6f9b154ef9', //固定为此 appid，不可改动
                extraData: res.data.data, // 包括 encrypt_card_id, outer_str, biz三个字段，须从 step3 中获得的链接中获取参数
                success: function(res) {
                    console.log(res,11)
                },
                fail: function(res) {
                    console.log(res)
                },
                complete: function(res) {
                    console.log(res,22)
                }
              })
        })
       
    },
    /* 跳转 */
    godistribution:function() {
       console.log(this.data.hasUserInfo)
        if(!this.data.hasUserInfo || !this.data.userInfo.nickName){
            return wx.showToast({
                title: '请先授权微信',
                icon: 'none',
                duration: 1500
            })
        }
        if (!this.data.phone) {
            return wx.showToast({
                title: '激活会员，享受更多折扣福利',
                icon: 'none',
                duration: 1500
            })
        }
        wx.navigateTo({
            url: '/pages/distribution/index'
        })
    }
})